<template>
	<view class="" style="width: 100%;">
		<view v-if="isNull" class="cart_null">
			<image src="../../static/images/cart/cart_null.png" mode=""></image>
			<text>购物车空空如也~</text>
			<button class="btn-shop-list" @tap="shopList()">去逛逛</button>
		</view>
		<view v-if="!isNull" style="width: 100%;">
			<scroll-view class="scroll" show-scrollbar='false' enable-flex scroll-y :style="{height:cartHeight+'px'}">
				<!-- 商品卡片 start -->
				<view class="product" style="margin:auto">
					<view v-for="(item,index) in cartList1" class="animated fadeIn">
						<!-- <text class="shopText" style="margin-left: 30rpx;color: #999999;">老年食堂</text> -->
						<view class="card" style="">
							<view class="ml-3">
								<view class="">
									<checkbox :checked="item.flag" @tap="_seletedAll(item.flag,index)" color="#ffffff"
										class="checkbox">
										<text class="shopText">
											{{item.shopName}}
										</text>

									</checkbox>
									<!-- 	<text class="iconfont check" @tap="_seletedAll(item.flag,index)" :class="item.flag?'icondagou':'icongouxuanzhong'">
										<text class="shopText">
											{{item.shopName}}
										</text>
									</text> -->
								</view>
								<view class="checkbox">
									<view class="top">
										<checkbox-group @change="seletedStatus(index,item.data.length,$event)" checked>
											<view class="d-flex mt-1" v-for="(it,index) in item.data">
												<checkbox :value="String(index)" :key="index" :checked="it.flag"
													color="#FFFFFF" class="list_checkbox">
												</checkbox>

												<view class="ml-2">
													<image class="rounded-20 image_icon" :src="it.goodsLogo"></image>
												</view>
												<view class="ml-5 d-block">
													<text>{{it.goodsName}}</text>
													<view class="d-flex mt-5">
														<view style="width: 200rpx;">
															<text class="text-pink font-md">{{it.goodsPrice}}积分</text>
														</view>
														<view class=" font-md ml-3" style="">
															<text class="iconfont iconminus-opp text-pink"
																@tap="addSubtractProduct(-1,it)"></text>
															<text class="p-2" style="width: 25rpx;">{{it.number}}</text>
															<text class="iconfont iconjia1 text-pink"
																style="margin-left: 0rpx;"
																@tap="addSubtractProduct(1,it)"></text>
														</view>
													</view>

												</view>
											</view>
										</checkbox-group>
									</view>
								</view>
							</view>

						</view>
					</view>
				</view>
			</scroll-view>
			<view class="bg-white calculate_view box d-jc-end d-ai-c">
				<!-- <checkbox class="pt-2 pl-2" value="" /> -->
				<text class="calculate_text_left">合计：
					<text style="color: #FF5551;">{{(price/100).toFixed(2)}}</text>
				</text>
				<text class="calculate_text text-white" @tap="subOrder">结算</text>
			</view>
		</view>
		<wybpopup ref="popup" type='bottom'>
			<view class="popup">
				<view class="pop-t">
					<image class="pop_images1" src="../../static/images/shoplist/guanbi@2x.png" mode="" @tap="close()"></image>
					<view>选择支付方式</view>
				</view>
				<view class="pop-c">
					<text>￥</text>
					<text>{{(price/100).toFixed(2)}}</text>
				</view>
				<radio-group @change="radioChange">
					<label class="uni-lab" v-for="(item, index) in items" :key="item.value">
						<view class="">
							<image v-if="item.value==='1'" class="pop_images2" src="../../static/images/shoplist/jfzf@2x.png" mode=""></image>
							<image v-if="item.value==='2'" class="pop_images2" src="../../static/images/shoplist/wxzf@2x.png" mode=""></image>
							<view class="pop-name">
								<text>{{item.name}}</text>
								<text v-if="item.value==='1'">(剩余{{userInfo.userInfo.accumulatePoints}}积分)</text>
							</view>
						</view>
						<view>
							<radio :value="item.value" :checked="index === current" />
						</view>
					</label>
				</radio-group>
				<button class="payment" type="default" @tap='payment1'>
					立即支付
				</button>
		
		
			</view>
		
		</wybpopup>
		
	</view>



</template>

<script>
	import wybpopup from '@/components/wyb-popup/wyb-popup.vue'
	import hansTabber from '../../components/hans-tabbar/hans-tabbar.vue'
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		components: {
			hansTabber,
			wybpopup
		},
		data() {
			return {
				items: [{
						value: '1',
						name: '积分支付'
					},
					{
						value: '2',
						name: '微信支付',
						checked: 'true'
					}
				
				],
				current: 0,
				tabbarHeight: 0,
				/* 底部tabbar数组 */
				current1: 2, //激活底部tabbar颜色
				seletedAll: [],
				cartHeight: 500, //元素的所需高度
				cartList1: '',
				userId: 1,
				checkList: [], //
				price: 0,
				isNull: false
			}
		},
		computed: mapState(['loginState','userInfo']),
		onNavigationBarButtonTap(e) {
			uni.navigateTo({
				url: '../index/index'
			})
		},
		onReady() {
			let that = this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					that.cartHeight = res.windowHeight - uni.upx2px(90) //windoHeight为窗口高度，主要使用的是这个


				}
			})
		},

		onShow() {
			this.getUserInfo()
			if(this.loginState){
				this.getCartList()
			}else{
				uni.navigateTo({
					url:'../user/login'
				})
			}

		},
		methods: {
			...mapMutations(['logout', 'setUserInfo']),
			// 获取用户信息
			getUserInfo() {
				
				console.log(this.loginState)
				console.log(this.userInfo)
				this.$api.getUserInfo().then((res) => {
					let userInfo = res.data.dataMap
					// this.getUserIn = res.data.dataMap
					console.log(userInfo)
					if (userInfo != null) {
						this.setUserInfo(userInfo)
					}
			
				})
			
			},
			radioChange: function(evt) {
				for (let i = 0; i < this.items.length; i++) {
					if (this.items[i].value === evt.detail.value) {
						this.current = i;
						break;
					}
				}
			},
			open() {
				// this.$refs.popup.open('bottom')
				this.$refs.popup.show()
			},
			close() {
				// this.$refs.popup.close()
				this.$refs.popup.hide()
				uni.showTabBar(); 
			},
			shopList() {
				uni.switchTab({
					url: '../shopList/shopList'
				})
			},
			subOrder() {
				let _this = this
				const parameter = {
					ids: [],
					dispatching: [], //数据传输使用 不参与后端交互
					isDispatching: '',
					shop: []
				}
				for (var i = 0; i < this.cartList1.length; i++) {
					for (var j = 0; j < this.cartList1[i].data.length; j++) {
						if (this.cartList1[i].data[j].flag) {
							parameter.ids.push(this.cartList1[i].data[j].goodsId)
							parameter.dispatching.push(this.cartList1[i].isDispatching)
							parameter.shop.push(this.cartList1[i].data[j].shopId)
							// parameter.dispatching.push(this.cartList1[i].isDispatching)
							// console.log(JSON.stringify("000000"+JSON.stringify()))
						}

					}
				}
				if (parameter.ids.length < 1) {
					uni.showToast({
						title: '请选择要结算的商品',
						duration: 1000,
						icon: "none"
					});
					return
				}
				let isDispatching = _this.uniq(parameter.dispatching)
				if (isDispatching.length > 1) {
					uni.showToast({
						title: '商家类型不同，不能同时结算！',
						duration: 2000,
						icon: "none"
					});
					return
				}
				if (isDispatching[0] == -1) {
					_this.open()
					uni.hideTabBar(); 
				}
				if (isDispatching[0] == 1) {
					let shop = _this.uniq(parameter.shop)
					if (shop.length > 1) {
						uni.showToast({
							title: '配送商家不能同时结算！',
							duration: 2000,
							icon: "none"
						});
						return
					}
					console.log(shop[0])
					//验证数组大小
					uni.navigateTo({
						url: '../order/address-order?shopId=' + shop[0] + '&goodsIds=' +
							JSON.stringify(parameter.ids)
					});
					return
				
				} 
				// uni.showModal({
				// 	title: '提示',
				// 	content: '确认支付？',
				// 	confirmColor: '#FF5551',
				// 	success: function(res) {
				// 		if (res.confirm) {
				// 			//判断页面跳转
				// 			console.log("--------------" + JSON.stringify(parameter))
				// 			let isDispatching = _this.uniq(parameter.dispatching)
				// 			if (isDispatching.length > 1) {
				// 				uni.showToast({
				// 					title: '商家类型不同，不能同时结算！',
				// 					duration: 2000,
				// 					icon: "none"
				// 				});
				// 				return
				// 			}
				// 			if (isDispatching[0] == -1) {
				// 				_this.open()
				// 				uni.hideTabBar(); 
				// 			}
				// 			if (isDispatching[0] == 1) {
				// 				let shop = _this.uniq(parameter.shop)
				// 				if (shop.length > 1) {
				// 					uni.showToast({
				// 						title: '配送商家不能同时结算！',
				// 						duration: 2000,
				// 						icon: "none"
				// 					});
				// 					return
				// 				}
				// 				console.log(shop[0])
				// 				//验证数组大小
				// 				uni.navigateTo({
				// 					url: '../order/address-order?shopId=' + shop[0] + '&goodsIds=' +
				// 						JSON.stringify(parameter.ids)
				// 				});
				// 				return

				// 			}




				// 		} else if (res.cancel) {
				// 			uni.showToast({
				// 				title: '已取消',
				// 				duration: 2000,
				// 				icon: "none"
				// 			});
				// 		}
				// 	}
				// });

			},
			//口腔支付 
			payment1(){
				const parameter = {
					ids: [],
					dispatching: [], //数据传输使用 不参与后端交互
					isDispatching: '',
					shop: []
				}
				for (var i = 0; i < this.cartList1.length; i++) {
					for (var j = 0; j < this.cartList1[i].data.length; j++) {
						if (this.cartList1[i].data[j].flag) {
							parameter.ids.push(this.cartList1[i].data[j].goodsId)
							parameter.dispatching.push(this.cartList1[i].isDispatching)
							parameter.shop.push(this.cartList1[i].data[j].shopId)
							// parameter.dispatching.push(this.cartList1[i].isDispatching)
							// console.log(JSON.stringify("000000"+JSON.stringify()))
						}
				
					}
				}
				let type=1
				if(this.current===0){
					type=1
				}
				if(this.current===1){
					type=2
				}
				parameter.isDispatching = -1
				this.$api.subOrder(parameter).then((res) => {
					// uni.hideLoading()
					console.log(JSON.stringify("0099999" + res))
					if (res.data.code == 200) {
						//订单提交成功 开始支付
						const parameter = {
							"orderNo": res.data.data.orderNumber
						}
						this.payOrder(parameter,type)
					} else {
						uni.showToast({
							title: res.data.msg,
							duration: 1000,
							icon: "none"
						});
					}
				})
			},
			uniq(array) {
				var temp = []; //一个新的临时数组
				for (var i = 0; i < array.length; i++) {
					if (temp.indexOf(array[i]) == -1) {
						temp.push(array[i]);
					}
				}
				return temp;
			},
			//订单支付
			payOrder(parameter,type) {
				parameter.type=type
				this.$api.payOrder(parameter).then((res) => {
					this.price = 0
					if(type==1){ //余额支付
						if (res.data.code == 200) {
							uni.showToast({
								title: '支付成功',
								duration: 1000,
								icon: "none"
							});
							this.close()
							setTimeout(function() {
								uni.navigateTo({
									url: '../pay/pay-state'
								});
							}, 1200);
						
						} else {
							uni.showToast({
								title: res.data.msg,
								duration: 1000,
								icon: "none"
							});
							setTimeout(function() {
								uni.navigateTo({
									url: '../pay/pay',
									success: res => {},
									fail: () => {},
									complete: () => {}
								});
						
							}, 1000);
						}
						
					}else if(type==2){
						uni.requestPayment({
							provider: "wxpay",
							orderInfo: res.data.data,
							success:(res)=> {
								uni.showToast({
									title: "支付成功",
									duration: 2500,
								});
								this.close()
								// setTimeout(function() {
								// 	uni.navigateTo({
								// 		url: '../pay/pay'
								// 	})
								// }, 1700);
						
							},
							fail(e) {
								console.log(e)
								uni.showToast({
									title: "支付失败",
									duration: 2000,
									icon: 'none',
								});
								// plus.nativeUI.alert(JSON.stringify(e), function() {
						
								// }, "提示", "关闭")
						
							}
						})
					}
					
				})

			},

			addSubtractProduct(status, item) {
				this.$api.addSubtractProduct({
					goodsId: item.goodsId,
					status: status
				}).then((res) => {
					console.log(JSON.stringify(res))
					if (res.statusCode == 200 && res.data.code == 200) {
						// debugger
						console.log(item)
						for (var i = 0; i < this.cartList1.length; i++) {
							if (this.cartList1[i].shopId == item.shopId) {
								for (var j = 0; j < this.cartList1[i].data.length; j++) {
									if (this.cartList1[i].data[j].goodsId == item.goodsId) {
										this.cartList1[i].data[j].number = this.cartList1[i].data[j].number +
											Number(status)
										console.log("====" + JSON.stringify(this.cartList1[i].data[j].number))
										if (this.cartList1[i].data[j].number == 0) {
											this.cartList1[i].data.splice(j, 1) //移除商品
											if (this.cartList1[i].data == '') {
												this.totalPrice()
												this.cartList1.splice(i, 1)
												// alert(this.cartList1.length)
												this.isNull = this.cartList1.length == 0 ? true : false
											}
											// console.log(JSON.stringify(this.cartList1[i].data))
										}
									}

								}

							}
						}
						this.totalPrice()
					}
				})

			},
			//价格统计
			totalPrice() {
				let price = 0
				for (var i = 0; i < this.cartList1.length; i++) {
					for (let j = 0; j < this.cartList1[i].data.length; j++) {
						if (this.cartList1[i].data[j].flag) {
							let data = this.cartList1[i].data[j];
							price = price + Number(data.goodsPrice) * 100 * data.number
						}
					}
				}
				this.price = price
				console.log("选中价格：" + price)
			},
			getCartList() {
				this.cartList1 = ''
				this.$api.getCartList({}).then((res) => {
					if (res.statusCode == 200) {
						this.cartList1 = res.data.data
						console.log(this.cartList1)
						this.price = 0
						uni.hideLoading()
						this.isNull = this.cartList1 == '' ? true : false
					}
				})
			},
			back() {
				uni.navigateBack({
					delta: 1,
					animationType: 'none',
					animationDuration: 200
				})
			},

			seletedStatus(index, length, e) {
				console.log("索引===：" + index)
				// console.log("数组长度：" + length)
				console.log('所选esuoyin==：' + JSON.stringify(e.detail.value))
				// console.log('pppp'+.length)
				console.log('dddd' + e.detail.value.length)
				for (var i = 0; i < this.cartList1[index].data.length; i++) {
					// this.cartList1[index].data[i]
					if (e.detail.value.includes(String(i))) {
						if (!this.cartList1[index].data[i].flag) {
							this.cartList1[index].data[i].flag = true
							this.price = this.price + parseFloat(this.cartList1[index].data[i].goodsPrice) * parseInt(this
								.cartList1[index].data[i].number) * 100
						}
					} else {
						if (this.cartList1[index].data[i].flag) {
							console.log("====局部修复===")
							this.cartList1[index].data[i].flag = false
							this.price = this.price - parseFloat(this.cartList1[index].data[i].goodsPrice) * parseInt(this
								.cartList1[index].data[i].number) * 100
						}
					}
				}


				if (length == e.detail.value.length) {
					this.cartList1[index].flag = true
				} else {
					this.cartList1[index].flag = false
				}
				console.log('------:' + JSON.stringify(this.cartList1))

			},
			_seletedAll(flag, index) {
				console.log(flag)
				console.log(index)
				if (!flag) {
					//勾选
					this.cartList1[index].flag = true
					for (var i = 0; i < this.cartList1[index].data.length; i++) {
						if (!this.cartList1[index].data[i].flag) {
							this.cartList1[index].data[i].flag = true
							this.price = this.price + Math.floor(parseFloat((this.cartList1[index].data[i].goodsPrice) *
								parseInt(this.cartList1[index].data[i].number)) * 100)
						}
					}

				} else {
					this.cartList1[index].flag = false
					for (var i = 0; i < this.cartList1[index].data.length; i++) {
						if (this.cartList1[index].data[i].flag) {
							this.cartList1[index].data[i].flag = false
							let nu = parseFloat((this.cartList1[index].data[i].goodsPrice) * parseInt(this.cartList1[index]
								.data[i].number)) * 100
							this.price = this.price - nu
						}

					}


				}

			}

		}
	}
</script>

<style scoped>
	.payment{
		width: 670rpx;
		height: 88rpx;
		background: #FF5551;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: 500;
		color: #FFFFFF;
		margin-top: 100rpx;
	}
	.pop-name>text:nth-child(1){
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-left: 13rpx;
	}
	.pop-name>text:nth-child(2){
		font-size: 32rpx;
		font-weight: 500;
		color: #999999;
		line-height: 120rpx;
	}
	.uni-lab>view:nth-child(1){
		margin-left: 20rpx;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	.uni-lab{
		width: 690rpx;
		height: 100rpx;
		margin: 0rpx auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 20rpx;
	}
	.pop_images2{
		width: 52rpx;
		height: 52rpx;
	}
	.pop-c{
		text-align: center;
		margin-bottom: 60rpx;
	}
	.pop-c>text:nth-child(1){
		font-size: 40rpx;
		font-weight: 800;
		color: #333333;
	}
	.pop-c>text:nth-child(2){
		font-size: 80rpx;
		font-weight: 800;
		color: #333333;
	}
	.pop-t{
		display: flex;
		align-items: center;
		text-align: center;
		margin-top: 40rpx;
	}
	.pop-t>view{
		font-size: 30rpx;
		font-weight: bold;
		color: #333333;
		margin-left: 210rpx;
	}
	.pop_images1{
		width: 48rpx;
		height: 48rpx;
		margin-left: 40rpx;
	}
	.popup {
		width: 750rpx;
		height: 785rpx;
		background: #FFFFFF;
		border-radius: 60rpx 60rpx 0rpx 0rpx;
		overflow: hidden;
		z-index: 9999;
	}
	.check {
		color: #FF5551;
		font-size: 40rpx;
	}

	.scroll {
		background-color: #F8F8F8;
	}

	.btn-shop-list {
		background-color: #FF5551;
		border-radius: 50rpx;
		width: 200rpx;
		color: #FFFFFF;
		line-height: 75rpx;
		margin-top: 40rpx;
	}

	.uni-modal {
		border-radius: 30rpx !important;
	}

	.cart_null {
		display: flex;
		width: 100%;
		flex-direction: column;
	}

	.cart_null text {
		margin: 0 auto;
		color: #666666;
	}

	.cart_null image {
		margin: 60rpx auto;
		width: 250rpx;
		height: 250rpx;
	}

	.calculate_text_left {}

	/* 结算文本样式 */
	.calculate_text {
		background-color: #FF5551;
		padding: 5rpx 30rpx;
		border-radius: 15rpx;
		margin: 0rpx 20rpx;
	}

	/* 结算view */
	.calculate_view {
		height: 80rpx;
		width: 100%;
		position: fixed;
		bottom: 0rpx;
		position: absolute;
		/* border: solid 1rpx #ffffff; */
	}

	.tabbar {
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	page {
		display: -webkit-box;
		width: 100%;
		height: 100%;
	}

	.scroll-view-item {
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.image_icon {
		width: 140upx;
		height: 140upx;
	}

	.list_checkbox {
		margin-top: 40upx;
	}

	.checkbox {
		margin-left: 20rpx;
		margin-top: 20rpx;
	}

	.shopText {
		font-size: 36rpx;
		font-weight: 550;
		margin-left: 10rpx;
		line-height: 36rpx;
		color: #333333;
	}

	.card {
		width: 700rpx;
		margin: 0 auto;
		/* height: 200rpx; */
		background-color: #ffffff;
		margin-top: 20rpx;
		border-radius: 10rpx;
		-moz-box-shadow: #909090 0px 0px 10px;
		/*firefox*/
		-webkit-box-shadow: #909090 0px 0px 1px;
		/*safari或chrome*/
		box-shadow: #bebebe 0px 0px 3px;
		/*opera或ie9*/
	}

	.status_bar {
		height: var(--status-bar-height);
		width: 100%;
		background-color: #FF5551;
	}
</style>
